package com.sccba.emtbusiness.service.impl;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import com.sccba.common.core.domain.entity.SysUser;
import com.sccba.common.exception.ServiceException;
import com.sccba.common.utils.DateUtils;
import com.sccba.common.utils.SecurityUtils;
import com.sccba.common.utils.StringUtils;
import com.sccba.common.utils.poi.ExcelUtil;
import com.sccba.emtbusiness.domain.YjczFbDuty;
import com.sccba.emtbusiness.domain.YjczFbInfo;
import com.sccba.emtbusiness.enums.DutyType;
import com.sccba.system.service.ISysUserService;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.internal.Engine;
import org.apache.xmlbeans.ResourceLoader;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sccba.emtbusiness.mapper.YjczDutyPersonMapper;
import com.sccba.emtbusiness.domain.YjczDutyPerson;
import com.sccba.emtbusiness.service.IYjczDutyPersonService;

import javax.servlet.http.HttpServletResponse;

/**
 * 发版值班人员Service业务层处理
 * 
 * @author lichh
 * @date 2024-04-28
 */
@Service
public class YjczDutyPersonServiceImpl implements IYjczDutyPersonService 
{
    @Autowired
    private YjczDutyPersonMapper yjczDutyPersonMapper;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询发版值班人员
     * 
     * @param pkId 发版值班人员主键
     * @return 发版值班人员
     */
    @Override
    public YjczDutyPerson selectYjczDutyPersonByPkId(Long pkId)
    {
        return yjczDutyPersonMapper.selectYjczDutyPersonByPkId(pkId);
    }

    /**
     * 查询发版值班人员列表
     * 
     * @param yjczDutyPerson 发版值班人员
     * @return 发版值班人员
     */
    @Override
    public List<YjczDutyPerson> selectYjczDutyPersonList(YjczDutyPerson yjczDutyPerson)
    {
        return yjczDutyPersonMapper.selectYjczDutyPersonList(yjczDutyPerson);
    }

    /**
     * 新增发版值班人员
     * 
     * @param yjczDutyPerson 发版值班人员
     * @return 结果
     */
    @Override
    public int insertYjczDutyPerson(YjczDutyPerson yjczDutyPerson)
    {
        yjczDutyPerson.setCreateTime(DateUtils.getNowDate());
        return yjczDutyPersonMapper.insertYjczDutyPerson(yjczDutyPerson);
    }

    /**
     * 修改发版值班人员
     * 
     * @param yjczDutyPerson 发版值班人员
     * @return 结果
     */
    @Override
    public int updateYjczDutyPerson(YjczDutyPerson yjczDutyPerson)
    {
        yjczDutyPerson.setUpdateTime(DateUtils.getNowDate());
        return yjczDutyPersonMapper.updateYjczDutyPerson(yjczDutyPerson);
    }

    /**
     * 批量删除发版值班人员
     * 
     * @param pkIds 需要删除的发版值班人员主键
     * @return 结果
     */
    @Override
    public int deleteYjczDutyPersonByPkIds(Long[] pkIds)
    {
        return yjczDutyPersonMapper.deleteYjczDutyPersonByPkIds(pkIds);
    }

    /**
     * 删除发版值班人员信息
     * 
     * @param pkId 发版值班人员主键
     * @return 结果
     */
    @Override
    public int deleteYjczDutyPersonByPkId(Long pkId)
    {
        return yjczDutyPersonMapper.deleteYjczDutyPersonByPkId(pkId);
    }

    @Override
    public List<YjczDutyPerson> getListByFbId(Long fbId) {
        List<YjczDutyPerson> list = yjczDutyPersonMapper.selectDutyPersonListByFbId(fbId);
        return list;
    }

    @Override
    public void saveDutyPersonList(List<YjczDutyPerson> list) {
        // 先删后插
//        if (null == list || list.isEmpty()) {
//            return;
//        }
//        Long dutyFbId = list.get(0).getDutyFbId();
//        yjczDutyPersonMapper.deleteByFbId(dutyFbId);
//        for (YjczDutyPerson person : list) {
//            person.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
//            person.setCreateTime(new Date());
//        }
//        yjczDutyPersonMapper.batchInsert(list);
    }

    @Override
    public void exportDutyByFbId(HttpServletResponse response, YjczFbInfo fbInfo) {
        Long fbId;
        if (null == fbInfo || null == (fbId = fbInfo.getPkId()) || 0 == fbId) {
            throw new ServiceException("无法获取需要导出的发版信息");
        }
        List<YjczDutyPerson> list = yjczDutyPersonMapper.selectDutyPersonListByFbId(fbId);
        if (null == list || list.isEmpty()) {
            throw new ServiceException("请先维护值班人员");
        }
        List<Map<String, Object>> firstMapList = new ArrayList<>();
        List<Map<String, Object>> secondMapList;
        Map<String, Object> map;
        Map<String, Object> secondMap;
        Map<String, Integer> firstIdxMap = new HashMap<>();
//        Map<String, Integer> secondIdxMap = new HashMap<>();
        List<String> personStrList = new ArrayList<>();
        for (YjczDutyPerson person : list) {
            String firstLevelGroupName = person.getDutyFirstLevelGroup();
            String secondLevelGroupName = person.getDutySecondLevelGroup();
            List<YjczFbDuty> fbDutyList = person.getFbDutyList();
            Integer idx = firstIdxMap.get(firstLevelGroupName);
            int size = fbDutyList.size();
            if (0 == size) {
                fbDutyList.add(new YjczFbDuty());
            } else {
                for (YjczFbDuty fbDuty : fbDutyList) {
                    SysUser devUser = fbDuty.getDevUser();
                    SysUser testUser = fbDuty.getTestUser();
                    appendPersonString(personStrList, devUser);
                    appendPersonString(personStrList, testUser);
                    makeNickNameForExport(fbDuty.getDevDutyType(), devUser);
                    makeNickNameForExport(fbDuty.getTestDutyType(), testUser);
                }
            }
            if (null == idx) {
                map = new HashMap<>();
                firstMapList.add(map);
                firstIdxMap.put(firstLevelGroupName, firstMapList.size() - 1);
                map.put("groupName", firstLevelGroupName);
                map.put("mergeCount", 0 == size ? 1 : size);
                secondMapList = new ArrayList<>();
                map.put("secondMapList", secondMapList);
                secondMap = new HashMap<>();
                secondMapList.add(secondMap);
                secondMap.put("groupName", secondLevelGroupName);
                secondMap.put("personList", fbDutyList);
            } else {
                map = firstMapList.get(idx);
                map.put("mergeCount", ((Integer) map.get("mergeCount")) + (0 == size ? 1 : size));
                secondMapList = (List<Map<String, Object>>) map.get("secondMapList");
                secondMap = new HashMap<>();
                secondMapList.add(secondMap);
                secondMap.put("groupName", secondLevelGroupName);
                secondMap.put("personList", fbDutyList);
            }
        }
        handleTeamLeaderAndGeneralControl(personStrList, fbInfo);
        Context context = new Context();
        context.putVar("personList", firstMapList);
        context.putVar("fbInfo", fbInfo);
        context.putVar("personString", personStrList.stream().collect(Collectors.joining(";")));
        ExcelUtil excelUtil = new ExcelUtil(YjczDutyPerson.class);
        Map<String, Object> funcs = new HashMap<>();
        funcs.put("DateUtils", new DateUtils()); // 添加自定义功能
        excelUtil.exportExcel(response, context, "dutyTemplate.xls", funcs);
    }
    private void handleTeamLeaderAndGeneralControl (List<String> list, YjczFbInfo fbInfo) {
        List<String> userIdList = new ArrayList<>();
        userIdList.add(String.valueOf(fbInfo.getFbTeamLeader()));
        String gcIds = fbInfo.getGcIds();
        String qcIds = fbInfo.getQcIds();
        setUserIdsInList(userIdList, gcIds);
        setUserIdsInList(userIdList, qcIds);
        if (userIdList.isEmpty()) {
            return;
        }
        List<SysUser> userList = userService.queryUserByUserIds(userIdList);
        for (SysUser sysUser : userList) {
            appendPersonString(list, sysUser);
        }
    }
    private void setUserIdsInList (List<String> userIdList, String ids) {
        if (StringUtils.isEmpty(ids)) {
            return;
        }
        String[] userIds = ids.split(",");
        for (String str : userIds) {
            userIdList.add(str);
        }
    }

    private void appendPersonString (List<String> list, SysUser sysUser) {
        String userName;
        if (null == sysUser || StringUtils.isEmpty(userName = sysUser.getUserName())) {
            return;
        }
        String person = sysUser.getNickName() + "(" + userName + ")";
        if (list.contains(person)) {
            return;
        }
        list.add(person);
    }
    private void makeNickNameForExport (Integer dutyType, SysUser sysUser) {
        if (null == sysUser || null == sysUser.getUserId()) {
            return;
        }
        sysUser.setNickName(sysUser.getNickName() + DutyType.getInfoByCode(dutyType));
    }

    private Map<String, Object> buildData (List<Map<String, Object>> mapList, Map<String, Integer> idxMap, String idxMapKey, String lvGroupName, List<YjczFbDuty> persons) {
        Integer idxInList = idxMap.get(idxMapKey);
        Map<String, Object> map;
        if (null == idxInList) {
            map = new HashMap<>();
            map.put("groupName", lvGroupName);
            map.put("personList", persons);
            mapList.add(map);
            idxMap.put(idxMapKey, mapList.size() - 1);
        } else {
            map = mapList.get(idxInList);
            List<YjczFbDuty> personList = (List<YjczFbDuty>) map.get("personList");
            personList.addAll(persons);
        }
        return map;
    }
}
